package com.example.myjavafx.controller;

import com.example.myjavafx.model.Product;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;

import java.net.URL;
import java.util.Optional;
import java.util.ResourceBundle;

/**
 * @author admin
 */
public class ProductController implements Initializable {

    @FXML
    private TextField idField;

    @FXML
    private TextField nameField;

    @FXML
    private TextField priceField;

    @FXML
    private TableView<Product> productTable;

    @FXML
    private TableColumn<Product, String> idColumn;

    @FXML
    private TableColumn<Product, String> nameColumn;

    @FXML
    private TableColumn<Product, Double> priceColumn;


    /**
     * 数据集合
     */
    private final ObservableList<Product> productList = FXCollections.observableArrayList();

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        // 设置列的单元格值工厂
        idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
        nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        priceColumn.setCellValueFactory(new PropertyValueFactory<>("price"));

        // 将数据集合绑定到表格
        productTable.setItems(productList);

        // 添加表格选择监听器
        productTable.getSelectionModel().selectedItemProperty().addListener(
                (observable, oldValue, newValue) -> showProductDetails(newValue));

        // 添加一些示例数据
        addSampleData();
    }

    // 添加示例数据
    private void addSampleData() {
        productList.add(new Product("P001", "笔记本电脑", 6999.00));
        productList.add(new Product("P002", "智能手机", 3999.00));
        productList.add(new Product("P003", "平板电脑", 2999.00));
    }

    // 显示选中产品的详细信息
    private void showProductDetails(Product product) {
        if (product != null) {
            idField.setText(product.getId());
            nameField.setText(product.getName());
            priceField.setText(String.valueOf(product.getPrice()));
        } else {
            idField.clear();
            nameField.clear();
            priceField.clear();
        }
    }

    // 处理添加按钮点击事件
    @FXML
    private void handleAdd() {
        if (validateInput()) {
            String id = idField.getText();
            String name = nameField.getText();
            double price = Double.parseDouble(priceField.getText());

            // 检查ID是否已存在
            boolean idExists = productList.stream()
                    .anyMatch(p -> p.getId().equals(id));

            if (idExists) {
                showAlert(Alert.AlertType.ERROR, "错误", "添加失败", "产品ID已存在！");
                return;
            }

            // 创建新产品并添加到列表
            Product newProduct = new Product(id, name, price);
            productList.add(newProduct);

            // 清空输入框
            handleClear();

            showAlert(Alert.AlertType.INFORMATION, "成功", "添加成功", "产品已成功添加！");
        }
    }

    // 处理修改按钮点击事件
    @FXML
    private void handleUpdate() {
        Product selectedProduct = productTable.getSelectionModel().getSelectedItem();

        if (selectedProduct == null) {
            showAlert(Alert.AlertType.WARNING, "警告", "未选择产品", "请先选择要修改的产品！");
            return;
        }

        if (validateInput()) {
            String id = idField.getText();
            String name = nameField.getText();
            double price = Double.parseDouble(priceField.getText());

            // 如果ID已更改，检查新ID是否已存在
            if (!selectedProduct.getId().equals(id)) {
                boolean idExists = productList.stream()
                        .anyMatch(p -> p.getId().equals(id) && p != selectedProduct);

                if (idExists) {
                    showAlert(Alert.AlertType.ERROR, "错误", "修改失败", "新产品ID已存在！");
                    return;
                }

                // ID已更改，需要移除旧产品并添加新产品
                productList.remove(selectedProduct);
                Product updatedProduct = new Product(id, name, price);
                productList.add(updatedProduct);
                productTable.getSelectionModel().select(updatedProduct);
            } else {
                // 只更新名称和价格
                selectedProduct.setName(name);
                selectedProduct.setPrice(price);
                productTable.refresh();
            }

            showAlert(Alert.AlertType.INFORMATION, "成功", "修改成功", "产品信息已成功更新！");
        }
    }

    // 处理删除按钮点击事件
    @FXML
    private void handleDelete() {
        Product selectedProduct = productTable.getSelectionModel().getSelectedItem();

        if (selectedProduct == null) {
            showAlert(Alert.AlertType.WARNING, "警告", "未选择产品", "请先选择要删除的产品！");
            return;
        }

        // 显示确认对话框
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("确认删除");
        alert.setHeaderText("删除产品");
        alert.setContentText("确定要删除产品 \"" + selectedProduct.getName() + "\" 吗？");

        Optional<ButtonType> result = alert.showAndWait();
        if (result.isPresent() && result.get() == ButtonType.OK) {
            // 从列表中删除产品
            productList.remove(selectedProduct);
            handleClear();
            showAlert(Alert.AlertType.INFORMATION, "成功", "删除成功", "产品已成功删除！");
        }
    }

    // 处理清空按钮点击事件
    @FXML
    private void handleClear() {
        idField.clear();
        nameField.clear();
        priceField.clear();
        productTable.getSelectionModel().clearSelection();
    }

    // 验证输入
    private boolean validateInput() {
        String errorMessage = "";

        if (idField.getText() == null || idField.getText().isEmpty()) {
            errorMessage += "产品ID不能为空！\n";
        }

        if (nameField.getText() == null || nameField.getText().isEmpty()) {
            errorMessage += "产品名称不能为空！\n";
        }

        if (priceField.getText() == null || priceField.getText().isEmpty()) {
            errorMessage += "价格不能为空！\n";
        } else {
            try {
                double price = Double.parseDouble(priceField.getText());
                if (price < 0) {
                    errorMessage += "价格不能为负数！\n";
                }
            } catch (NumberFormatException e) {
                errorMessage += "价格必须是有效的数字！\n";
            }
        }

        if (errorMessage.isEmpty()) {
            return true;
        } else {
            showAlert(Alert.AlertType.ERROR, "输入错误", "请修正以下错误", errorMessage);
            return false;
        }
    }

    // 显示提示框
    private void showAlert(Alert.AlertType alertType, String title, String header, String content) {
        Alert alert = new Alert(alertType);
        alert.setTitle(title);
        alert.setHeaderText(header);
        alert.setContentText(content);
        alert.showAndWait();
    }
}
